<template>
  <div class="screen-designer-container h-screen flex flex-col bg-gray-50">
    <el-container>
      <!-- 顶部工具栏 -->

      <el-header class="h-14 border-b bg-white shadow-sm flex items-center justify-between px-6">
        <div class="flex items-center gap-4">
          <h1 class="text-xl font-bold text-gray-800">大屏设计器</h1>
          <el-divider direction="vertical" class="h-8" />
          <el-button-group>
            <el-button size="small" icon="el-icon-save" @click="handleSave">保存</el-button>
            <el-button size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
            <el-button size="small" icon="el-icon-view" @click="togglePreview">预览</el-button>
          </el-button-group>
        </div>

        <div class="flex items-center gap-4">
          <el-switch v-model="showGrid" active-text="显示网格" inactive-text="隐藏网格" @change="handleGridChange" />
          <el-switch v-model="snapToGrid" active-text="吸附网格" inactive-text="取消吸附" />
          <el-input-number v-model="gridSize" :min="10" style="height: 20px;" :max="100" :step="10" size="small"
            label="网格大小" />
        </div>
      </el-header>




      <el-container>
        <!-- 左侧组件库 -->
        <el-aside v-if="!isPreview" style="width: 80px;" class="h-full overflow-auto bg-white border-r">
          <div class="p-2">
            <h2 class="text-lg font-semibold mb-2 text-gray-700 text-center">组件</h2>

            <div class="mb-4">
              <h3 class="text-xs font-medium text-gray-500 mb-1 text-center">基础</h3>
              <div class="grid grid-cols-3 gap-4">
                <!-- 每个draggable-component改为圆形按钮样式，只显示图标 -->
                <draggable-component type="text" label="文本" @add="addNewComponent">
                  <template #icon>
                    <Icon icon="icon-park:text" />
                  </template>
                </draggable-component>

                <draggable-component type="image" icon="icon-park:text" label="图片" @add="addNewComponent" />
                <draggable-component type="rectangle" icon="el-icon-crop" label="矩形" @add="addNewComponent" />
                <draggable-component type="circle" icon="el-icon-circle-check" label="圆形" @add="addNewComponent" />
                <draggable-component type="line" icon="el-icon-minus" label="线条" @add="addNewComponent" />
                <draggable-component type="button" icon="el-icon-button" label="按钮" @add="addNewComponent" />
              </div>
            </div>

            <div class="mb-4">
              <h3 class="text-xs font-medium text-gray-500 mb-1 text-center">图表</h3>
              <div class="grid grid-cols-2 gap-1">
                <draggable-component type="bar-chart" icon="el-icon-data-analysis" label="柱状图" @add="addNewComponent" />
                <draggable-component type="line-chart" icon="el-icon-data-line" label="折线图" @add="addNewComponent" />
                <draggable-component type="pie-chart" icon="el-icon-data-pie" label="饼图" @add="addNewComponent" />
                <draggable-component type="gauge-chart" icon="el-icon-data-board" label="仪表盘" @add="addNewComponent" />
                <draggable-component type="radar-chart" icon="el-icon-data-radar" label="雷达图" @add="addNewComponent" />
                <draggable-component type="table" icon="el-icon-table" label="表格" @add="addNewComponent" />
              </div>
            </div>

            <div>
              <h3 class="text-xs font-medium text-gray-500 mb-1 text-center">容器</h3>
              <div class="grid grid-cols-2 gap-1">
                <draggable-component type="container" icon="el-icon-container" label="容器" @add="addNewComponent" />
                <draggable-component type="tabs" icon="el-icon-tabs" label="标签页" @add="addNewComponent" />
                <draggable-component type="card" icon="el-icon-card" label="卡片" @add="addNewComponent" />
              </div>
            </div>
          </div>
        </el-aside>
        <!-- 中间画布区域 -->
        <el-main :class="{ 'ml-0': isPreview }">
          <div :style="{
            width: `${canvasWidth}px`,
            height: `${canvasHeight}px`,
            background: canvasBackground,
            backgroundImage: showGrid ? `linear-gradient(to right, rgba(0, 0, 0, 0.05) ${gridSize}px, transparent ${gridSize}px), linear-gradient(to bottom, rgba(0, 0, 0, 0.05) ${gridSize}px, transparent ${gridSize}px)` : 'none',
            backgroundSize: showGrid ? `${gridSize}px ${gridSize}px` : 'auto'
          }">
          
            <div>
              <template v-for="(component, index) in components" :key="component.id">
                <component-wrapper :component="component" :index="index" :snap-to-grid="snapToGrid"
                  :grid-size="gridSize" :is-selected="selectedComponentId === component.id" :is-preview="isPreview"
                  @select="handleComponentSelect" @update="handleComponentUpdate" @remove="handleComponentRemove"
                  @z-index-up="handleZIndexUp(index)" @z-index-down="handleZIndexDown(index)" />
              </template>
            </div>

           
            <div v-if="isPreview" class="absolute top-4 right-4 bg-black/50 text-white px-3 py-1 rounded text-sm">
              预览模式
            </div>
          </div>

        
        </el-main>

        <!-- 右侧属性面板 -->
        <el-aside style="width: 200px;" v-if="!isPreview && selectedComponentId">
          <div class="p-4">
            <div class="flex justify-between items-center mb-4">
              <h2 class="text-lg font-semibold text-gray-700">组件属性</h2>
              <el-button size="mini" icon="el-icon-delete" @click="handleComponentRemove(selectedComponentId)" />
            </div>

            <component-properties :component="selectedComponent" @update="handlePropertyUpdate" />
          </div>
        </el-aside>



      </el-container>

    </el-container>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { ElIcon, ElMessage, ElMessageBox } from 'element-plus';

import VueDraggableResizable from 'vue-draggable-resizable';
import 'vue-draggable-resizable/style.css'
import { v4 as uuidv4 } from 'uuid';
import { useScreenStore } from '/@/stores/screenStore';


// 导入 Icon 组件
import { Icon } from '@iconify/vue'

// 导入组件
import DraggableComponent from '/@/components/container/DraggableComponent.vue';
import ComponentWrapper from '/@/components/container/ComponentWrapper.vue';
import ComponentProperties from '/@/components/container/ComponentProperties.vue';

// 导入图表组件

import LineChart from '/@/components/charts/LineChart.vue';
import PieChart from '/@/components/charts/PieChart.vue';
// import GaugeChart from '/@/components/charts/GaugeChart.vue';
// import RadarChart from '/@/components/charts/RadarChart.vue';
// import TableComponent from '/@/components/charts/TableComponent.vue';
// import BarChart from '/@/components/charts/BarChart.vue';

// 导入基础组件
import TextComponent from '/@/components/basic/TextComponent.vue';
import ImageComponent from '/@/components/basic/ImageComponent.vue';
import RectangleComponent from '/@/components/basic/RectangleComponent.vue';
import CircleComponent from '/@/components/basic/CircleComponent.vue';
import LineComponent from '/@/components/basic/LineComponent.vue';
import ButtonComponent from '/@/components/basic/ButtonComponent.vue';

// 导入容器组件
import ContainerComponent from '/@/components/container/ContainerComponent.vue';
// import TabsComponent from '/@/components/container/TabsComponent.vue';
// import CardComponent from '/@/components/container/CardComponent.vue';

export default {
  components: {
    VueDraggableResizable,
    DraggableComponent,
    ComponentWrapper,
    ComponentProperties,
    Icon,
    //BarChart,
    LineChart,
    PieChart,
    // GaugeChart,
    // RadarChart,
    // TableComponent,
    TextComponent,
    ImageComponent,
    RectangleComponent,
    CircleComponent,
    LineComponent,
    ButtonComponent,
    ContainerComponent,
    // TabsComponent,
    // CardComponent
  },
  setup() {
    // 初始化 Pinia Store（关键：Pinia 直接实例化，无需 dispatch）
    const screenStore = useScreenStore();

    // 原有状态管理（保持不变）
    const components = ref([]);
    const selectedComponentId = ref(null);
    const showGrid = ref(true);
    const snapToGrid = ref(true);
    const gridSize = ref(20);
    const isPreview = ref(false);
    const canvasWidth = ref(1920);
    const canvasHeight = ref(1080);
    const canvasBackground = ref('#ffffff');
    const screenId = ref('');

    // 获取选中组件（保持不变）
    const selectedComponent = computed(() => {
      return components.value.find(item => item.id === selectedComponentId.value) || null;
    });

    // 初始化：从 URL 取 ID 并加载大屏数据（适配 Pinia）
    onMounted(async () => {
      const urlParams = new URLSearchParams(window.location.search);
      screenId.value = urlParams.get('id') || '';
      if (screenId.value) {
        await loadScreenData(); // 调用下方适配 Pinia 的加载函数
      } else {
        components.value = [];
      }
    });

    // 修复1：加载大屏数据（Pinia 直接调用 actions 函数，替换 Vuex dispatch）
    const loadScreenData = async () => {
      try {
        // Pinia：直接调用 store 中的 actions（无需 dispatch）
        const response = await screenStore.getScreenById(screenId.value);
        if (response.success) {
          // 从 Pinia state 取数据（或直接用 response.data，二选一）
          const screenData = screenStore.currentScreen;
          components.value = screenData.components || [];
          canvasWidth.value = screenData.width || 1920;
          canvasHeight.value = screenData.height || 1080;
          canvasBackground.value = screenData.background || '#ffffff';
          showGrid.value = screenData.showGrid || true;
          gridSize.value = screenData.gridSize || 20;
        } else {
          ElMessage.error('加载大屏数据失败: ' + response.message);
        }
      } catch (error) {
        console.error('加载大屏数据出错:', error);
        ElMessage.error('加载大屏数据时发生错误');
      }
    };

    // 修复2：保存大屏（适配 Pinia，直接调用 create/update 函数）
    const handleSave = async () => {
      try {
        const screenData = {
          id: screenId.value,
          width: canvasWidth.value,
          height: canvasHeight.value,
          background: canvasBackground.value,
          showGrid: showGrid.value,
          gridSize: gridSize.value,
          components: components.value
        };

        let response;
        if (screenId.value) {
          // Pinia：更新大屏（直接调用 updateScreen 动作）
          response = await screenStore.updateScreen(screenData);
        } else {
          // Pinia：创建新大屏（直接调用 createScreen 动作）
          response = await screenStore.createScreen(screenData);
          if (response.success) {
            // 从 Pinia state 取新大屏 ID（或 response.data.id）
            screenId.value = screenStore.currentScreen.id;
          }
        }

        if (response.success) {
          ElMessage.success('保存成功');
        } else {
          ElMessage.error('保存失败: ' + (response.message || '未知错误'));
        }
      } catch (error) {
        console.error('保存大屏出错:', error);
        ElMessage.error('保存大屏时发生错误: ' + error.message);
      }
    };

    // 添加新组件
    const addNewComponent = (type) => {
      // 组件默认属性
      const defaultComponents = {
        text: {
          type: 'text',
          label: '文本',
          x: 100,
          y: 100,
          width: 200,
          height: 50,
          content: '双击编辑文本',
          fontSize: 16,
          color: '#333333',
          textAlign: 'center',
          backgroundColor: 'transparent',
          zIndex: components.value.length + 1
        },
        image: {
          type: 'image',
          label: '图片',
          x: 100,
          y: 200,
          width: 300,
          height: 200,
          src: 'https://picsum.photos/300/200',
          alt: '图片',
          zIndex: components.value.length + 1
        },
        rectangle: {
          type: 'rectangle',
          label: '矩形',
          x: 100,
          y: 450,
          width: 200,
          height: 150,
          backgroundColor: '#409eff',
          borderRadius: 4,
          borderWidth: 0,
          borderColor: '#333333',
          zIndex: components.value.length + 1
        },
        circle: {
          type: 'circle',
          label: '圆形',
          x: 350,
          y: 100,
          width: 150,
          height: 150,
          backgroundColor: '#67c23a',
          borderWidth: 0,
          borderColor: '#333333',
          zIndex: components.value.length + 1
        },
        line: {
          type: 'line',
          label: '线条',
          x: 350,
          y: 300,
          width: 200,
          height: 2,
          strokeColor: '#f56c6c',
          strokeWidth: 2,
          zIndex: components.value.length + 1
        },
        button: {
          type: 'button',
          label: '按钮',
          x: 350,
          y: 350,
          width: 120,
          height: 40,
          text: '按钮',
          backgroundColor: '#409eff',
          color: '#ffffff',
          borderRadius: 4,
          zIndex: components.value.length + 1
        },
        'bar-chart': {
          type: 'bar-chart',
          label: '柱状图',
          x: 500,
          y: 100,
          width: 500,
          height: 300,
          title: '柱状图示例',
          data: {
            labels: ['一月', '二月', '三月', '四月', '五月'],
            datasets: [{
              label: '数据1',
              data: [12, 19, 3, 5, 2]
            }, {
              label: '数据2',
              data: [5, 10, 15, 20, 25]
            }]
          },
          zIndex: components.value.length + 1
        },
        'line-chart': {
          type: 'line-chart',
          label: '折线图',
          x: 500,
          y: 450,
          width: 500,
          height: 300,
          title: '折线图示例',
          data: {
            labels: ['一月', '二月', '三月', '四月', '五月'],
            datasets: [{
              label: '数据1',
              data: [12, 19, 3, 5, 2]
            }]
          },
          zIndex: components.value.length + 1
        },
        'pie-chart': {
          type: 'pie-chart',
          label: '饼图',
          x: 1050,
          y: 100,
          width: 300,
          height: 300,
          title: '饼图示例',
          data: {
            labels: ['A', 'B', 'C', 'D'],
            datasets: [{
              data: [30, 20, 40, 10]
            }]
          },
          zIndex: components.value.length + 1
        },
        container: {
          type: 'container',
          label: '容器',
          x: 1050,
          y: 450,
          width: 400,
          height: 300,
          title: '容器',
          backgroundColor: '#f5f7fa',
          borderWidth: 1,
          borderColor: '#e4e7ed',
          borderRadius: 4,
          zIndex: components.value.length + 1,
          children: []
        }
        // 可以继续添加其他组件的默认配置
      };

      // 检查组件类型是否存在
      if (!defaultComponents[type]) {
        ElMessage.warning('组件类型不存在');
        return;
      }

      // 创建新组件并添加到列表
      const newComponent = {
        id: uuidv4(),
        ...defaultComponents[type]
      };

      components.value.push(newComponent);
      // 选中新添加的组件
      selectedComponentId.value = newComponent.id;
    };

    // 处理组件选择
    const handleComponentSelect = (id, event) => {
      event.stopPropagation();
      selectedComponentId.value = id;
    };

    // 处理组件更新（位置和大小）
    const handleComponentUpdate = (id, props) => {
      const index = components.value.findIndex(item => item.id === id);
      if (index !== -1) {
        components.value[index] = {
          ...components.value[index],
          ...props
        };
      }
    };

    // 处理组件属性更新
    const handlePropertyUpdate = (props) => {
      if (!selectedComponentId.value) return;

      const index = components.value.findIndex(item => item.id === selectedComponentId.value);
      if (index !== -1) {
        components.value[index] = {
          ...components.value[index],
          ...props
        };
      }
    };

    // 移除组件
    const handleComponentRemove = (id) => {
      ElMessageBox.confirm('确定要删除这个组件吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        components.value = components.value.filter(item => item.id !== id);
        if (selectedComponentId.value === id) {
          selectedComponentId.value = null;
        }
        ElMessage.success('组件已删除');
      }).catch(() => {
        // 取消删除
      });
    };

    // 调整组件层级（上移）
    const handleZIndexUp = (index) => {
      if (index >= components.value.length - 1) return;

      // 交换位置
      const temp = components.value[index];
      components.value[index] = components.value[index + 1];
      components.value[index + 1] = temp;

      // 更新z-index
      components.value[index].zIndex = index + 1;
      components.value[index + 1].zIndex = index + 2;
    };

    // 调整组件层级（下移）
    const handleZIndexDown = (index) => {
      if (index <= 0) return;

      // 交换位置
      const temp = components.value[index];
      components.value[index] = components.value[index - 1];
      components.value[index - 1] = temp;

      // 更新z-index
      components.value[index].zIndex = index + 1;
      components.value[index - 1].zIndex = index;
    };

    // 处理网格显示切换
    const handleGridChange = (value) => {
      showGrid.value = value;
    };



    // 导出大屏配置
    const handleExport = () => {
      const screenData = {
        width: canvasWidth.value,
        height: canvasHeight.value,
        background: canvasBackground.value,
        components: components.value
      };

      const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(screenData, null, 2));
      const downloadAnchorNode = document.createElement('a');
      downloadAnchorNode.setAttribute("href", dataStr);
      downloadAnchorNode.setAttribute("download", `screen-design-${new Date().getTime()}.json`);
      document.body.appendChild(downloadAnchorNode);
      downloadAnchorNode.click();
      downloadAnchorNode.remove();

      ElMessage.success('导出成功');
    };

    // 切换预览模式
    const togglePreview = () => {
      isPreview.value = !isPreview.value;
      // 预览模式下取消选中状态
      if (isPreview.value) {
        selectedComponentId.value = null;
      }
    };





    return {
      components,
      selectedComponentId,
      selectedComponent,
      showGrid,
      snapToGrid,
      gridSize,
      isPreview,
      canvasWidth,
      canvasHeight,
      canvasBackground,


      addNewComponent,
      handleComponentSelect,
      handleComponentUpdate,
      handlePropertyUpdate,
      handleComponentRemove,
      handleZIndexUp,
      handleZIndexDown,
      handleGridChange,
      handleSave,
      handleExport,
      togglePreview
    };
  }
};
</script>

<style scoped>
.screen-designer-container {
  overflow: hidden;
}

.screen-canvas {

  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
  margin-bottom: 20px;
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .screen-canvas {
    transform: scale(0.8);

  }
}

@media (max-width: 1200px) {
  .screen-canvas {
    transform: scale(0.6);

  }
}
</style>
